package servlet;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import pojo.User;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/PaginationServlet")
public class UserPageServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String URL = "jdbc:mysql://localhost:3306/people";
    private static final String USER = "root";
    private static final String PASSWORD = "nmnm1239";
    private static final int PAGE_SIZE = 10; // 每页显示10条记录

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int currentPage = 1;
        int pageSize = 10; // 默认每页显示10条记录
        String searchKeyword = request.getParameter("searchKeyword");
        String searchColumn = request.getParameter("searchColumn");

        if (request.getParameter("page") != null) {
            currentPage = Integer.parseInt(request.getParameter("page"));
        }
        if (request.getParameter("pageSize") != null) {
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        }

        List<User> users = new ArrayList<>();
        int totalRecords = 0;
        int totalPages = 0;

        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD)) {
            String countQuery = "SELECT COUNT(*) FROM user";
            // 如果有搜索关键词，则构建带搜索条件的 SQL 查询语句
            if (searchKeyword != null && !searchKeyword.isEmpty() && searchColumn != null && !searchColumn.isEmpty()) {
                countQuery += " WHERE " + searchColumn + " LIKE ?";
            }
            try (PreparedStatement countStmt = connection.prepareStatement(countQuery)) {
                // 如果有搜索关键词，则设置查询参数
                if (searchKeyword != null && !searchKeyword.isEmpty() && searchColumn != null && !searchColumn.isEmpty()) {
                    countStmt.setString(1, "%" + searchKeyword + "%");
                }
                ResultSet rs = countStmt.executeQuery();
                if (rs.next()) {
                    totalRecords = rs.getInt(1);
                }
            }

            totalPages = (int) Math.ceil((double) totalRecords / pageSize);

            String query = "SELECT * FROM user";
            // 如果有搜索关键词，则构建带搜索条件的 SQL 查询语句
            if (searchKeyword != null && !searchKeyword.isEmpty() && searchColumn != null && !searchColumn.isEmpty()) {
                query += " WHERE " + searchColumn + " LIKE ?";
            }
            query += " LIMIT ? OFFSET ?";
            try (PreparedStatement stmt = connection.prepareStatement(query)) {
                int paramIndex = 1;
                // 如果有搜索关键词，则设置查询参数
                if (searchKeyword != null && !searchKeyword.isEmpty() && searchColumn != null && !searchColumn.isEmpty()) {
                    stmt.setString(paramIndex++, "%" + searchKeyword + "%");
                }
                stmt.setInt(paramIndex++, pageSize);
                stmt.setInt(paramIndex++, (currentPage - 1) * pageSize);
                ResultSet rs = stmt.executeQuery();
                while (rs.next()) {
                    User user = new User();
                    user.setId(rs.getInt("id"));
                    user.setUsername(rs.getString("username"));
                    user.setEmail(rs.getString("email"));
                    users.add(user);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        JSONObject responseData = new JSONObject();
        responseData.put("totalPages", totalPages);
        responseData.put("users", users);
        responseData.put("totalRecords", totalRecords); // 添加总记录数

        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        out.println(responseData);
        out.close();
    }
}
